<?php
/**
 * 用户系统是单独的系统,不考虑权限问题
 * @author wolf
 * @since 2014-07-12
 *
 */
class MemberService {
	// 系统默认管理员 权限从上到下 默认是5
	public $_group = array (1 => "SUPER", 2 => "ADMIN", 3 => "VERIFY", 4 => "LOGIN", 5 => "VISIT", 6 => "BLACK", 0 => "FORWARD" );
	// 用户最基本的属性
	public $_user = array ('uid' => null, 'username' => null, 'groupid' => NULL );
	// 用户扩展属性
	public $_user_extend = array ('realname' => null );
	private $_num = 40; //分页数
	// 用来区分等级
	public $_copoun = "groupid";
	// 用户等级制度
	public $_rank = array ("幼儿园" => 0, "学前班" => 20, "小学生" => 30, "初中生" => 40, "高中生" => 50, "大学生" => 60, "博士生" => 70 );
	public $_verify = array ("-1" => "不通过", "0" => "尚未认证", "1" => "实名认证" );
	public $_status = array ("0" => "在职", "1" => "离职" );
	//0审核中 1不通过 
	public $_face = array ("/static/attached/face/1.jpg", "/static/attached/face/2.jpg" );
	//存储头像的路径
	private $_savefacePath = "/static/attached/face/";
	public function getGroup() {
		return MemberModel::instance ()->getGroupAll ();
	}
	
	/**
	 * 增加用户
	 */
	public function add($userInfo) {
		//检查手机 是否被注册过
		if (! $this->checkRepeat ( 'mobile_phone', $userInfo ['mobile_phone'] )) {
			return "重复了!";
		}
		
		$salt = $this->randstr ();
		$data ['username'] = trim ( $userInfo ['username'] );
		$data ['real_name'] = trim ( $userInfo ['real_name'] );
		$data ['password'] = md5 ( md5 ( $userInfo ['password'] ) . $salt );
		$data ['salt'] = $salt;
		$data ['add_time'] = time ();
		$ip = $this->getIp ();
		$data ['ip'] = $ip ['ip'];
		$data ['area'] = $ip ['country'] . $ip ['city'];
		$data ['mobile_phone'] = trim ( $_POST ['mobile_phone'] );
		//防止非法修改
		$data ['groupid'] = trim ( $_POST ['groupid'] ) > 10 ? trim ( $_POST ['groupid'] ) : 10;
		$gremark = MemberModel::instance ()->getOneGroup ( array ('id' => $data ['groupid'] ) );
		$data ['remark'] = $gremark ['name'];
		$data ['verify'] = 0; //直接验证成功
		MemberModel::instance ()->addMember ( $data );
		return "success";
	}
	
	public function getMemberGroup() {
		return MemberModel::instance ()->getGroupAll ();
	}
	//加密方法
	protected function randstr($len = 6) {
		$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
		// characters to build the password from 
		mt_srand ( ( double ) microtime () * 1000000 * getmypid () );
		// seed the random number generater (must be done) 
		$password = '';
		while ( strlen ( $password ) < $len )
			$password .= substr ( $chars, (mt_rand () % strlen ( $chars )), 1 );
		return $password;
	}
	/**
	 * 检查用户是否重复
	 */
	public function checkRepeat($key, $value) {
		$rs = MemberModel::instance ()->getOneMember ( array ($key => trim ( $value ) ) );
		
		if (! empty ( $rs )) {
			
			return false;
		}
		return true;
	}
	
	/**
	 * 判断是否登录
	 * @param String $username
	 * @param String $passsword
	 */
	public function isLogin($username, $passsword) {
		
		//下面调用服务
		// 查询用户是否存在
		$userInfo = MemberModel::instance ()->getOneMember ( array ('mobile_phone' => $username ) );
		// 简单验证
		if (empty ( $username )) {
			return "用户不存在";
		}
		if (strlen ( $username ) < 4 || strlen ( $passsword ) < 4) {
			return "用户名或密码不能小与6位!";
		}
		// 判断密码是否正确
		if ($userInfo ['password'] != md5 ( md5 ( $passsword ) . $userInfo ['salt'] )) {
			return "密码不正确";
		
		}
		//检查账号是否被禁用
		if ($userInfo ['status'] > 0) {
			return "账号已被禁用!";
		}
		
		return $userInfo;
	
	}
	
	public function addLoginLog($userInfo) {
		//增加登录历史记录
		$actioname = empty ( $userInfo ['real_name'] ) ? $userInfo ['username'] : $userInfo ['real_name'];
		$address = $this->getIp ();
		$area = $address ['country'] . $address ['area'];
		$params = array ('action' => "登录", 'uid' => $userInfo ['uid'], 'username' => $actioname, 'address' => $area, 'ip' => $address ['ip'], 'date' => time () );
		//增加登录日志
		LogModel::instance ()->addLog ( $params );
		//最后登录时间
		MemberModel::instance ()->setMemberByWhere ( array ('lastlogin' => time () ), array ('uid' => $userInfo ['uid'] ) );
	}
	/**
	 * 获取随机头像
	 * Enter description here ...
	 * @param unknown_type $num
	 */
	public function getRandFace($num) {
		return MemberModel::instance ()->getRandFace ( $num );
	}
	/**
	 * 获取ip
	 */
	protected function getIp() {
		$ip = new IpLocation ();
		$clientIp = $ip->getIP ();
		$rs = $ip->getlocation ( $clientIp );
		unset ( $rs ['beginip'] );
		unset ( $rs ['endip'] );
		foreach ( $rs as $k => $v ) {
			$v = iconv ( 'GB2312', 'UTF-8', $v );
			$arrIp [$k] = $v;
		}
		return $arrIp;
	}
	
	/**
	 * 验证头像
	 * @param int $id
	 * @param String $type
	 */
	public function validFace($id, $type) {
		$face = MemberModel::instance ()->getOneFace ( array ('id' => $id ) );
		$uid = $face ['uid'];
		if ($type == 'pass') {
			//修改头像
			$this->saveFace ( $face ['face'], $uid, 1 );
			//删除申请
			MemberModel::instance ()->delFaceOne ( array ('id' => $id ) );
			return true;
		} else {
			MemberModel::instance ()->delFaceOne ( array ('id' => $id ) );
			//删除图片
			unlink ( getcwd () . $face ['face'] );
			//并提示没有通过
			$this->saveFace ( $this->_face [1], $uid, 0 );
			return false;
		}
	}
	/**
	 * 获取所有提交的头像审核
	 */
	public function getVaildFaceList() {
		return MemberModel::instance ()->getFaceList ();
	}
	
	public function getOneMemberByUsername($username) {
		return MemberModel::instance ()->getOneMember ( array ('username' => $username ) );
	}
	/**
	 * 
	 * 搜索
	 */
	public function search($field, $value) {
		$rs = MemberModel::instance ()->getMemberByLike ( $field, $value );
		// 重组验证和等级
		foreach ( $rs as $k => $v ) {
			$rs [$k] ['verify'] = $this->_verify [$v ['verify']];
			$rs [$k] ['groupid'] = $this->_group [$v ['groupid']];
			$rs [$k] ['status'] = $this->_status [$v ['status']];
			if ($v == 'coupons') {
				// $rs[$k]['rank']=>$this->_rank[$v];
			}
		}
		return $rs;
	}
	/**
	 * 获取用户的登录状态  用与图表显示
	 * Enter description here ...
	 * @param unknown_type $format
	 * @param unknown_type $days
	 */
	public function getMemberLoginStatus($format, $days) {
		switch ($format) {
			case "m" :
				$f = "%Y%m";
				break;
			case "d" :
				$f = "%Y%m%d";
				break;
			default :
				$f = "%Y%m%d";
				break;
		}
		$rs = MemberModel::instance ()->tjLogin ( $days, $f ); //统计30的数据
		$rs = array_reverse ( $rs );
		$keys = '';
		$values = '';
		foreach ( $rs as $k => $v ) {
			$keys .= substr ( $v ['m'], 5, strlen ( $v ['m'] ) ) . ",";
			$values .= $v ['num'] . ",";
		}
		$keys = substr ( $keys, 0, - 1 );
		$values = substr ( $values, 0, - 1 );
		return array ('keys' => $keys, 'values' => $values );
	}
	/**
	 * 删除会员
	 * Enter description here ...
	 * @param int $uid
	 */
	public function remove($uid) {
		return MemberModel::instance ()->delMemberByWhere ( array ('uid' => $uid ) );
	}
	/**
	 * 上传头像 采用美图秀秀流上传
	 * Enter description here ...
	 * @param int $uid
	 * @param String $username
	 */
	public function uploadFace($uid, $username) {
		/**
		 * Note:for octet-stream upload
		 * 这个是流式上传PHP文件
		 * Please be amended accordingly based on the actual situation
		 */
		$post_input = 'php://input';
		$dir = date ( "Ym", time () );
		$url_path = $this->_savefacePath . $dir . "/";
		$save_path = getcwd () . $url_path;
		if (! is_dir ( $save_path )) {
			mkdir ( $save_path, 0777 );
		}
		$postdata = file_get_contents ( $post_input );
		if (isset ( $postdata ) && strlen ( $postdata ) > 0) {
			$name = uniqid () . '.jpg';
			$filename = $save_path . $name;
			$handle = fopen ( $filename, 'w+' );
			fwrite ( $handle, $postdata );
			fclose ( $handle );
			if (is_file ( $filename )) {
				$params = array ('face' => $url_path . $name, 'uid' => $uid, 'username' => $username );
				MemberModel::instance ()->addFaceList ( $params );
				$this->saveFace ( $this->_face [0], $uid, 0 );
				// echo 'Image data save successed,file:' . $filename;
				return true;
			} else {
				die ( 'Image upload error!' );
			}
		} else {
			die ( 'Image data not detected!' );
		}
	}
	public function listing($currentPage, $data) {
		$num = $this->_num;
		$where = null;
		$flag = false;
		$group = $this->getGroup ();
		//系统组别
		$groupname = array (0 => "All" );
		foreach ( $group as $v ) {
			$groupname [$v ['id']] = $v ['name'];
		}
		foreach ( $data as $k => $v ) {
			if (! empty ( $v ) && $k != "p" && $k != "mb") {
				$where [$k] = $v;
			}
		}
		$totalNum = MemberModel::instance ()->countMember ( $where );
		// $totalNum = NewsModel::instance ()->getCommentNum ( 'id', $cid );
		$page = $this->page ( $currentPage, $totalNum );
		$memberlist = MemberModel::instance ()->getPages ( $page ['start'], $page ['num'], $where, "uid DESC" );
		// 重组验证和等级
		foreach ( $memberlist as $k => $v ) {
			$memberlist [$k] ['verify'] = $this->_verify [$v ['verify']];
			$memberlist [$k] ['groupid'] = $this->_group [$v ['groupid']];
			$memberlist [$k] ['status'] = $this->_status [$v ['status']];
			if ($v == 'coupons') {
				// $rs[$k]['rank']=>$this->_rank[$v];
			}
		}
		return array ('totalnum' => $totalNum, 'memberlist' => $memberlist, 'groupname' => $groupname, 'verify' => $this->_verify, 'page' => $page );
	}
	/**
	 * 生成图片缩略图
	 *
	 * @param string $src
	 * 原图地址
	 * @param string $savePath
	 * 缩略图保存地址
	 * @param integer $width
	 * 缩略图宽
	 * @param integer $height
	 * 缩略图高
	 * @return string 缩略图地址
	 */
	private function buildThumb($src, $savePath, $width = 360, $height = 360) {
		$arr = getimagesize ( $src );
		if (! is_array ( $arr )) {
			return false;
		}
		// 1,2,3分别为gif,jpg,png
		if ($arr ['2'] > 4) {
			return false;
		}
		$func = 'imagecreatefrom';
		switch ($arr ['2']) {
			case 1 :
				$func .= 'gif';
				break;
			case 2 :
				$func .= 'jpeg';
				break;
			case 3 :
				$func .= 'png';
				break;
			default :
				$func .= 'jpeg';
		}
		$srcIm = $func ( $src );
		$im = imagecreatetruecolor ( $width, $height );
		imagecopyresized ( $im, $srcIm, 0, 0, 0, 0, $width, $height, $arr ['0'], $arr ['1'] );
		imagejpeg ( $im, $savePath );
		imagedestroy ( $srcIm );
		imagedestroy ( $im );
		return true;
	}
	/**
	 * 设置图 并且设置等级为1
	 * Enter description here ...
	 * @param unknown_type $v
	 * @param unknown_type $where
	 */
	public function saveFace($path, $uid, $level = 0) {
		return MemberModel::instance ()->setMemberByWhere ( array ('face' => $path, 'level' => $level ), array ('uid' => $uid ) );
	}
	
	/**
	 * 修改密码
	 * @param unknown_type $uid
	 * @param unknown_type $password
	 */
	public function rePasssword($uid, $password) {
		$salt = MemberModel::instance ()->getOneMember ( array ('uid' => trim ( $uid ) ) );
		MemberModel::instance ()->setMemberByWhere ( array ('password' => md5 ( md5 ( $password ) . $salt ['salt'] ) ), array ('uid' => trim ( $uid ) ) );
	}
	
	/**
	 * 上传缩略图
	 * 注意上传文件大小限制
	 *
	 * @return string $filePath 图片路径
	 */
	public function setFace() {
		if (is_uploaded_file ( $_FILES ['Filedata'] ['tmp_name'] )) {
			$upfile = $_FILES ['Filedata'];
			$name = $upfile [name];
			$type = $upfile [type];
			$size = $upfile [size];
			$tmp_name = $upfile [tmp_name];
			$error = $upfile [error];
			$fileType = substr ( $name, strpos ( $name, "." ) + 1 );
			switch ($fileType) {
				case 'jpeg' :
					$ok = 1;
					break;
				case 'jpg' :
					$ok = 1;
					break;
				case 'gif' :
					$ok = 1;
					break;
				case 'png' :
					$ok = 1;
				case 'doc' :
					$ok = 1;
				case 'txt' :
					$ok = 1;
				case 'xls' :
					$ok = 1;
				case 'ppt' :
					$ok = 1;
					break;
			}
			if ($ok == '1' && $error == '0') {
				$fileType = substr ( $name, strpos ( $name, "." ) + 1 );
				$newName = time () . "." . $fileType;
				$dir = date ( "Ym", time () );
				$filepath = "/static/attached/face/" . $dir;
				/*
                if (! is_dir($dir)) {
                    mkdir($filepath);
                }
                */
				$filepath = $filepath . DIRECTORY_SEPARATOR . $newName;
				move_uploaded_file ( $tmp_name, getcwd () . $filepath );
				$this->buildThumb ( getcwd () . $filepath, getcwd () . $filepath, 160, 160 );
				return $filepath;
			
		// $this->redirect ( '添加成功!', '/news/index' );
			} else {
				return false;
			
		// $this->redirect('文件类型不符合!', '/member/manage');
			}
		}
	}
	/**
	 * 分页
	 *
	 * @return void
	 */
	protected function page($p, $total) {
		$num = $this->_num;
		$pageid = isset ( $p ) ? $p : 1;
		$rs = $pageid * $num - $total;
		$start = ($pageid - 1) * $num;
		$pagenum = ceil ( $total / $num );
		$page = array ('start' => $start, 'num' => $num, 'current' => $pageid, 'page' => $pagenum );
		return $page;
	}
}